<?php
namespace app\admin\controller;

use think\facade\View;
use think\facade\Env;

use app\admin\model\SysUser as SysUserModel;
use app\admin\model\SysRole as SysRoleModel;

class SysUser extends Base
{
    public function index()
    {
        $data = SysUserModel::where('is_del', 0)
            ->field('id,username,role_id,truename,email,create_time,status')
            ->select();

        $dataRole = SysRoleModel::column('name','id');

        return View::fetch('index', [
            'data' => $data,
            'dataRole' => $dataRole
        ]);
    }
    
    public function info($id = 0)
    {
        if ($id != 0) {
            $data = SysUserModel::find($id);
        } else {
            $data = ['id'=>0, 'username' => '', 'role_id' => 0, 'truename' => '', 'email' => '', 'note' => ''];
        }

        $dataRole = SysRoleModel::column('name','id');

        return  View::fetch('save',[
            'data' => $data,
            'dataRole' => $dataRole
        ]);
    }

    public function save()
    {
        if ($this->app->request->isPost()) {
            $param = $this->app->request->param();
            if ($param['username'] =='' || $param['role_id'] =='') {
                $this->error("用户名 or 角色 不能为空!");
            }
            try {
                if ($param['id'] != 0) {
                    $sysUser = SysUserModel::find($param['id']);
                    if (!empty($param['password'])) {
                        $password = $param['password'];
                        $sysUser->salt = generate_stochastic_string();
                        $sysUser->password = md5($password . $sysUser->salt);
                    }
                } else {
                    $sysUser = new SysUserModel();
                    $sysUser->salt = generate_stochastic_string();
                    $password = empty($param['password']) ? Env::get('sys.default_password') : $param['password'];
                    $sysUser->password = md5($password . $sysUser->salt);
                    $sysUser->create_time = time();
                }
                $sysUser->username = $param['username'];
                $sysUser->role_id = intval($param['role_id']);
                $sysUser->truename = $param['truename'];
                $sysUser->email = $param['email'];
                $sysUser->note = $param['note'];

                $sysUser->save();
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误代码:".$msg);
            }
            $this->success('操作成功', 'sys_user/index');
        }
    }

    public function isAvailable($id = null, $username = '')
    {
        if ($this->app->request->isAjax()) {
            $data = SysUserModel::where('username', $username)->find();
            if ($data && $data->id != $id) {
                return ['code' => 2, 'msg'=>'用户名已存在, 请使用其他用户名'];
            } else {
                return ['code' => 0, 'msg'=>'用户名可用'];
            }
        }
    }

    public function delete($id = null)
    {
        if ($this->app->request->isAjax()) {
            if (is_array($id)) {
                if (in_array(session('uid'), $id)) {
                    return ['code'=>0,'msg'=>'当前登录用户无法删除'];
                }
            } else {
                if ($id == session('uid')) {
                    return ['code'=>0,'msg'=>'当前登录用户无法删除'];
                }
            }
            if (SysUserModel::destroy($id)) {
                return ['code' => 1,'msg'=>'删除成功'];
            } else {
                return ['code' => 0,'msg'=>'删除失败'];
            }
        }
    }

    // 停用or启用管理员
    public function status($id, $status)
    {
        if ($this->app->request->isAjax()) {
            if ($id == session('uid')) {
                return ['code'=>0,'msg'=>'当前登录用户无法停用'];
            }
            if (SysUserModel::update(['status' => $status], ['id' => $id])) {
                return ['code'=>1,'msg'=>'操作成功'];
            } else {
                return ['code'=>0,'msg'=>'操作失败'];
            }
        }
    }

    //修改密码
    public function modifyPwd()
    {
        if ($this->app->request->isPOST()) {
            $params = $this->app->request->param();
            
            $info = SysUserModel::field(true)->find($this->uid);

            $oldpwd = md5($params['oldpassword'].$info->salt);
            if ($info->password != $oldpwd) {
                $this->error('原密码不正确');
            }

            if ($params['newpassword']!=$params['repassword']) {
                $this->error('两次新密码不一致，请核查');
            }
            $info->salt = generate_stochastic_string();
            $info->password = md5($info->salt . $params['newpassword']);

            if ($info->save()) {
                session(null);
                $this->success("修改成功,请重新登陆", 'login/index');
            } else {
                $this->error('修改失败，请稍后重试');
            }
        } else {
            return View::fetch();
        }
    }
}
